#include "ticker.h"
#include "math.h"

Ticker::Ticker() : m_UpdateSpeed(1.0f), m_Display(0.0f), m_Real(0.0f)
{
}

Ticker::~Ticker()
{
}

void Ticker::Init(float Start, float fUpdateSpeed, bool bReset)
{
	m_Real = Start;
	m_UpdateSpeed = fUpdateSpeed;

	if (m_UpdateSpeed < 0.0f) m_UpdateSpeed = -m_UpdateSpeed;
	if (bReset) m_Display = m_Real;
}

bool Ticker::Tick(float dt)
{
	if (m_Display < m_Real)
	{
		m_Display += dt * m_UpdateSpeed;
		if (m_Display > m_Real) {
			m_Display = m_Real;
			return false;
		}
		return true;
	}
	else if (m_Display > m_Real)
	{
		m_Display -= dt * m_UpdateSpeed;
		if (m_Display < m_Real) {
			m_Display = m_Real;
			return false;
		}
		return true;
	}

	return false;
}

// ------------------------------------------------------------------------------------------------------------------------

AccTicker::AccTicker() : m_Acceleration(1.0f), m_DesiredUpdate(1.0f)
{
}

AccTicker::~AccTicker()
{
}

void AccTicker::Init(float Start, float fUpdateSpeed, bool bReset)
{
	m_DesiredUpdate = fUpdateSpeed;
	Ticker::Init(Start, 0.0f, bReset);
}

bool AccTicker::Tick(float dt)
{
	bool bResult = Ticker::Tick(dt);

	if (!bResult) {
		m_UpdateSpeed -= dt * m_Acceleration;
		if (m_UpdateSpeed < 0.0f)
			m_UpdateSpeed = 0.0f;
	}
	else if (m_UpdateSpeed < m_DesiredUpdate) {
		m_UpdateSpeed += dt * m_Acceleration;
		if (m_UpdateSpeed > m_DesiredUpdate)
			m_UpdateSpeed = m_DesiredUpdate;
	}

	return bResult;
}

// ------------------------------------------------------------------------------------------------------------------------

AutoTicker::AutoTicker() : m_MaxUpdateTime(1.0f)
{
}

AutoTicker::~AutoTicker()
{
}

bool AutoTicker::Tick(float dt)
{
	float diff = fabs(m_Display - m_Real);

	if ((diff > 0.0f) && ((diff * m_MaxUpdateTime) > m_UpdateSpeed))
	{
		// accelerate the update speed
		return Ticker::Tick((dt * diff * m_MaxUpdateTime) / m_UpdateSpeed);
	}

	return Ticker::Tick(dt);
}
